﻿using FileSC.Configs;
using FileSC.DB.Entities;
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FileSC.DB.Database
{
    public class DownloadJobDB : IDisposable
    {
        internal LiteDatabase db { get; set; }
        internal ILiteCollection<DownloadJobInfo> tb_info { get; set; }
        internal static IDictionary<Guid, long> ProgressMap { get; set; }
        static DownloadJobDB()
        {
            ProgressMap = new Dictionary<Guid, long>();
        }
        public DownloadJobDB() : base()
        {
            var db_path = AppConfig.Text("下载记录库");

            db = new LiteDatabase(db_path);
            tb_info = db.GetCollection<DownloadJobInfo>();
            tb_info.EnsureIndex(x => x.JobID, true);
            tb_info.EnsureIndex(x => x.CreateTime);
            tb_info.EnsureIndex(x => x.UpdatedTime);
        }

        public void Dispose()
        {
            db.Dispose();
        }

        public IEnumerable<DownloadJobInfo> GetInfos()
        {
            return tb_info.FindAll().Select(info =>
            {
                if (ProgressMap.ContainsKey(info.JobID))
                {
                    try
                    {
                        info.DownloadSize = ProgressMap[info.JobID];
                    }
                    catch
                    {
                        ;// 多线程错误 不处理，可以忽略
                    }
                }
                return info;
            });
        }

        public void Update(DownloadJobInfo info)
        {
            DBHost.Link(info);
            tb_info.Upsert(info);
            db.Commit();
        }

        public DownloadJobInfo Update(Guid id, Func<DownloadJobInfo, DownloadJobInfo> func)
        {
            var info = FindByInfoId(id);
            info = func(info);
            info.UpdatedTime = DateTime.Now;
            Update(info);
            db.Commit();
            return info;
        }

        public void SetDownloadSize(Guid id, long size)
        {
            ProgressMap[id] = size;
        }

        public void ClearDownloadSize(Guid id)
        {
            ProgressMap.Remove(id);
        }

        public DownloadJobInfo FindByInfoId(Guid id)
        {
            var info = tb_info.FindById(id);

            if (ProgressMap.ContainsKey(id))
            {
                info.DownloadSize = ProgressMap[id];
            }
            return info;
        }

    }
}
